package huhx.linux.com.kotlinlearn

import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import huhx.linux.com.kotlinlearn.activity.SecondActivity
import huhx.linux.com.kotlinlearn.model.UserEvent
import huhx.linux.com.kotlinlearn.service.ICookService
import huhx.linux.com.kotlinlearn.utils.RxAndroidUtils
import huhx.linux.com.kotlinlearn.utils.ServiceCacheUtils
import huhx.linux.com.kotlinlearn.utils.ToastUtils
import io.reactivex.Observable
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 1、自定义一个Layout和View的过程
 * 2、ConstraintLayout这个Layout有什么优点，idea默认使用的就是这个
 */
class MainActivity : AppCompatActivity() {
    val LOG_TAG = this.javaClass.simpleName
    var observable: Observable<String>? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        EventBus.getDefault().register(this)

        btn_click.setOnClickListener({
            val cookService = ServiceCacheUtils.getService(ICookService::class.java)
            val requestMap = hashMapOf("menu" to "红烧肉", "key" to "76b05ed015ae69b5e84d3b896ee850ed")
            val serviceCall = cookService.getCookByMenu(requestMap)

            serviceCall.compose(RxAndroidUtils.rxSchedulerHelper())
                    .subscribe({ result ->
                        if (result.isSuccess()) {
                            ToastUtils.longShow(this, result.returnMsg)
                            Log.d(LOG_TAG, result.toString())
                        }
                    }, { error ->
                        tv_show.text = error.message
                    })
//                    .subscribe(object : SuccessConsumer<MoviceResponse>(this) {
//                        override fun accpet(response: MoviceResponse) {
//
//                        }
//                    }, object : ErrorConsumer(this) {})

        })

        btnRxbus.setOnClickListener({
            EventBus.getDefault().postSticky(UserEvent("huhx", "1234"))
            Thread.sleep(10000)
            startActivity(Intent(this, SecondActivity::class.java))
        })


        //        btnConsumer.setOnClickListener( {
//            observable = RxBus.get().register("huhx", String::class.java)
//            observable?.subscribe( { t ->
//                ToastUtils.longShow(this, "show " + t)
//            })
//        })
//    }
//

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    fun onMoonEvent(userevent: UserEvent) {
        Log.d("huhx", "name = $userevent")
    }
}
